package com.cvte.sunkit.ui.base

import android.annotation.SuppressLint
import android.content.res.Resources
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import com.cvte.sunkit.model.PerfData

/**
 *  @PackageName com.cvte.sunkit.ui.base
 *  @Description
 *  @Author lixu
 *  @Data 2023/7/21 10:54
 *  @Version 1.0
 */
abstract class BaseWindow {

    private lateinit var layoutParams: WindowManager.LayoutParams

    @Suppress("DEPRECATION")
    fun initLayoutParams(): WindowManager.LayoutParams {


        layoutParams = WindowManager.LayoutParams()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            this.layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE
        }
        layoutParams.format = PixelFormat.RGBA_8888
        layoutParams.gravity = Gravity.START or Gravity.TOP
        layoutParams.flags =
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE

        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT

        layoutParams.x = 0
        layoutParams.y = 0

        return layoutParams
    }

    abstract fun addView()

    abstract fun removeView()


    abstract fun updateUI(data: PerfData, resources: Resources)


    /**
     * 悬浮窗口拖动的事件监听
     */
    protected inner class FloatingOnTouchListener(private val windowManager: WindowManager) :
        View.OnTouchListener {
        private var x = 0
        private var y = 0

        @SuppressLint("ClickableViewAccessibility")
        override fun onTouch(view: View, event: MotionEvent): Boolean {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    x = event.rawX.toInt()
                    y = event.rawY.toInt()
                }

                MotionEvent.ACTION_MOVE -> {
                    val nowX = event.rawX.toInt()
                    val nowY = event.rawY.toInt()
                    val movedX = nowX - x
                    val movedY = nowY - y
                    x = nowX
                    y = nowY
                    layoutParams.x = layoutParams.x + movedX
                    layoutParams.y = layoutParams.y + movedY
                    windowManager.updateViewLayout(view, layoutParams) // 更新位置
                }

                else -> {}
            }
            return false
        }
    }
}